<template>
	<view class="content">
			<view>
				<view class="header-location">
					<view class="locaticon" @click="showMulLinkageTwoPicker">
						<text class="name">{{matterText}}</text>
					</view>
				</view>
				<mpvue-picker :themeColor="themeColor" ref="mpvuePicker" mode="selector" deepLength="1" :pickerValueDefault="pickerValueDefault"
				@onConfirm="onConfirm" :pickerValueArray="departmentList"></mpvue-picker>
				<mpvue-picker :themeColor="themeColor" ref="SelectEmployee" mode="selector" deepLength="1" :pickerValueDefault="pickerValueDefault"
				@onConfirm="onSelectEmployee" :pickerValueArray="employee"></mpvue-picker>
			</view>
			<!-- 输入框 -->
			<view class="mui-input-row">
				<textarea class="textarea" type="search" v-model="matterTxt" rows="5" placeholder="请说明一下您遇到的问题…"></textarea>
			</view>
			<!-- 上传照片 -->
			<view class="upload-pictures">上传图片  (最多添加6张图片)</view>
			<view class="img-wapper">
				<view class="preview" v-for="(item,index) in listImg" :key="index" v-if="listImg.length > 0">
					<text class="delete" @click="deleteClick(index)"></text>
					<image :src="item" @click="getItemImgClick(index)" />
				</view>
				<view class="button" @click="addImgClick"></view>
			</view>
			<!--录音-->
			<view class="record-wapper">
				<view class="record-item" @click="playVoice(item.uri)" v-for="(item,index) in recordList" :key="index" :style="'width:'+ item.divWidth+'px'">
					<image class="record-icon" src="../../../static/images/wifi.png" />
					<view>{{item.num}}″</view>
				</view>
			</view>
		<view class="botton-wapper">
			<view class="botton-record" @touchstart="startRecord" @touchend="endRecord"> <text class="mui-icon mui-icon-mic"></text>
				按住说话</view>
			<view class="botton-text" @click="submitClick">提交</view>
		</view>
		<record-popup v-if="isStatePup" :text="isStateText"></record-popup>
	</view>
</template>

<script>
	import mpvuePicker from '../../../components/mpvue-picker/mpvuePicker.vue'
	import recordPopup from '../../../components/report-matter/recordPopup.vue'
	
	import util from "../../../utils/util.js"
	import { reportMatterModule } from "../../../modules/reportMatter.js"
	import { mapMutations } from 'vuex'

	const reportMatter = new reportMatterModule()
	const recorderManager = uni.getRecorderManager()
	const innerAudioContext = uni.createInnerAudioContext()
	innerAudioContext.autoplay = true;

	export default {
		components: {
			mpvuePicker,
			recordPopup
		},
		data() {
			return {
				matterText: '选择相关报事人',
				pickerValueDefault: [0], // picker 索引 
				themeColor: '#2A89F8', // 确定按钮的颜色
				departmentList: [], // 初始化 部门数组
				employee: [], // 初始化 员工数组
				swiperHinget: '', // 定义页面的高
				picker: true, // 关闭picker 框
				leaderID: '', // 报事指定负责人id
				matterTxt: '', // 输入文本框
				listImg: [], // 上传图片列表
				Timer: null, // 录音计时器对象
				top: 0, // 初始化滚动模块的 滚动条位置
				isStateText: '录音中',
				isStatePup: false, // 录音窗口
				recordNum: 0, // 录音计时器 
				recordList: [] // 录音列表
			};
		},
		watch: {
			listImg(val) {
				if (val.length > 6) {
					util.tost('最多只能上传6张图片')
				}
			}
		},

		onLoad() {
			let Info = util.getSystemInfo() //获取设备信息
			this.swiperHinget = `height:${Info.windowHeight}px`;
			this.onRecordStop() // 监听录音停止事件
			let neiID = util.getStorage('neiID')
			reportMatter.GetOrganization(neiID) // 请求部门数据
				.then((res) => {
					this.departmentList = this._listEach(res) // 赋值部门
				})
		},

		onNavigationBarButtonTap() { // 监听右上角点击按钮事件
			uni.navigateTo({
				url: '/pages/ReportMatter/history/history'
			})
		},

		methods: {
			...mapMutations(['isUpdate']), // 调用vuex 里的方法
			
			showMulLinkageTwoPicker() { // 点击picker栏显示 picker
			console.log('asa')
				this.$refs.mpvuePicker.show()
			},
			onConfirm(e) { // 部门选择确定按钮 
				this.matterText = e.label
				let orgID = e.value[0] 
				this.getEmployee(orgID) // 根据部门 id 请求对应的员工 数据
			},
			getEmployee(orgID) { // 请求员工数据
				reportMatter.GetEmployee(orgID)
					.then((res) => {
						this.employee = this._listEach(res) // 赋值员工
						this.$refs.SelectEmployee.show() // 显示新的picker
					})
			},
			onSelectEmployee(e) { // 员工选择确定事件
				this.matterText = `${this.matterText} / ${e.label}`
				let leaderID = e.value[0]
				this.leaderID = leaderID
			},
			addImgClick() { // 添加照片 
				let dListImg = this.listImg
				// #ifdef APP-PLUS
				var that = this
				// 从相册中选择图片
				plus.gallery.pick((e) => {

					that.listImg = dListImg.concat(e.files)

					if (that.listImg.length > 6) {
						let num = that.listImg.length - 6
						that.listImg = that.listImg.slice(num)
					}

				}, (e) => {}, {
					filter: 'image',
					multiple: true,
					maximum: 6,
					system: false,
					onmaxed() {
						plus.nativeUI.alert('最多只能选择6张图片');
					}
				});
				// #endif

				// #ifdef MP-WEIXIN
				uni.chooseImage({
					count: 6,
					sizeType: ['original', 'compressed'],
					success: (res) => {
						let list = res.tempFilePaths
						if (list instanceof(Array)) { // 判断返回图片数据 是否为数据 
							this.listImg = list
						} else {
							this.listImg = this._stringOrList(list) // 转化数组方法
						}
					}
				})
				// #endif
			},
			getItemImgClick(index) { // 查看图片

				var listImg = this.listImg
				// #ifdef APP-PLUS
				plus.nativeUI.previewImage(listImg, {
					current: index
				})
				// #endif

				// #ifdef MP-WEIXIN
				uni.previewImage({
					urls: listImg,
					count: index
				})
				// #endif

			},
			deleteClick(num) { // 删除照片
				this.listImg.splice(num, 1)
			},


			startRecord() { // 长按录音方法 
				if (this.recordList.length == 3) {
					util.tost('录音输入最多三条')
					return
				}
				console.log('触摸了')
				recorderManager.start({ //设置录音文件格式为 mp3
						format: 'mp3'
					}),
					this.isStatePup = true
				this.Timer = setInterval(() => { // 计算录音时长 
					this.recordNum++
				}, 1000)
				this.top = 0 // 将滚动条位置初始化
			},

			endRecord() { // 离开按钮结束录音方法 
				console.log('触摸离开')
				recorderManager.stop(); // 停止结束录音
				clearInterval(this.Timer) // 停止录音计时器
				this.top = util.getSystemInfo().windowHeight - 95 // 将滚动条设置为最底端
			},

			onRecordStop() {
				recorderManager.onStop((res) => { // 监听录音停止事件
					this.isStatePup = false // 关闭录音窗口
					let num = this.recordNum // 获取录音时长
					if (num > 2) {
						let htmlWidth = util.getSystemInfo().windowWidth // 获取设备容器宽度 
						this.recordList.push({
							uri: res.tempFilePath, // 录音文件临时路径
							num: num, // 录音时长
							divWidth: num * (htmlWidth / 30) + 30 // 根据时长动态的设置 语音 item 的宽度
						})
						this.recordNum = 0 // 将时长初始化为零
					} else {
						this.recordNum = 0
						util.tost('录音太短了')
					}
				})
				innerAudioContext.onEnded((res) => { // 监听语音播放完成事件
					this.isStatePup = false
					this.isStateText = '录音中'
				})
			},

			playVoice(path) { // 播放录音
				if (path) {
					innerAudioContext.src = path
					innerAudioContext.play()
					this.isStatePup = true
					this.isStateText = '播放中'
				}
			},

			// 			DeleteVoice(index) { // 长按删除当前语音
			// 				let that = this
			// 				uni.showModal({
			// 					content: '确定删除当前语音？',
			// 					success: (res) => {
			// 						if (res.confirm) {
			// 							that.recordList.splice(index, 1)
			// 						} 
			// 					}
			// 				})
			// 			},

			submitClick() { // 提交工单方法
				if (!this.leaderID) {
					util.tost('请先选择报事部门和相关人')
					return
				}
				let that = this
				uni.showModal({
					content: '确定要提交吗？',
					success: (res) => {
						if (res.confirm) {
							that.submitOrder() // 提交报事工单
						}
					}
				})

			},

			submitOrder() { // 上传提交报事工单
				reportMatter.postReport(this.leaderID, this.matterTxt)
					.then((res) => {
						if (this.listImg.length > 0) {
							reportMatter.postPicture(res, this._filterList(this.listImg, 'picture')) // 提交图片方法
								.then((res) => {
									console.log('图片上传成功', res)
								})
						}
						if (this.recordList.length > 0) {
							reportMatter.postRecord(res, this._filterList(this.recordList, 'record')) //提交录音方法
								.then((res) => {
									console.log('录音上传成功', res)
								})
						}
						uni.showToast({
							icon: 'success',
							title: '提交报事成功！'
						})
						this.isUpdate() // 将 vuex 里的值 update改为true  , 只有updata值为true时才更新页面 
						setTimeout(() => {
							uni.navigateBack()
						}, 1000)
					})
			},

			_filterList(list, typeName) { // 转换设置数据元素对象
				let newList = []
				list.forEach((item, index) => {
					newList.push({
						uri: item.uri ? item.uri : item,
						name: typeName + index
					})
				})
				return newList
			},

			_stringOrList(images) { // 字符串转换数组 
				let imgList = images.split(',')
				return imgList
			},
			_listEach(dataList) { // 处理返回数据，按照picker 数据格式重新赋值
				var list = []
				dataList.forEach(function(item, index) {
					let {
						label,
						value
					} = {
						label: item.orgName || item.empName,
						value: item.orgID || item.userID,
					}
					list.push({
						label,
						value
					})
				})
				return list
			}
		},
		onBackPress() { // 监听用户点击返回键 销毁picker组件
			this.picker = false
		},
		onHide() { // 监听页面隐藏点击返回键 销毁picker组件
			this.picker = false
		}
	}
</script>

<style lang="scss" scoped>
	@import "../../../common/scss/common.scss";

	@import "index.scss";
</style>
